package io.netty.example.mytest.io;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;

/**
 * @ClassName BioSingleServer
 * @Description TODO
 * @Author dukezeng
 * @CreatedTime 2019/4/13 15:50
 * @Version 1.0
 **/
public class BioSingleServer {
    public static void main(String[] args) {
        new BioSingleServer().start();
    }

    public void start() {
        Socket socket = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            ServerSocket server = new ServerSocket(99);

            while(true) {
                //阻塞等待，直到有新的连接
                socket = server.accept();
                //阻塞等待，直到有数据可读
                inputStream = socket.getInputStream();
                byte[] buffer = new byte[1024];

                if (inputStream != null) {
                    inputStream.read(buffer);
                    System.out.println(new String(buffer));
                }

                outputStream = socket.getOutputStream();
                outputStream.write("server ack!".getBytes());

                inputStream.close();
                outputStream.close();
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream !=null ) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
